package HomePage

import (
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/User/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"time"
)

type GetHomePage struct {
	beego.Controller
}

func (c *GetHomePage) GetHomePage() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Activity/GetActivity"
	res := resMes.GetActivitys{}
	activitys := []*Admin.Activity{}
	log := &error2.Log{}
	var err error
	var sql string
	o := orm.NewOrm()

	homePagesAddr, err := c.GetInt("addr", 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	if homePagesAddr == 3 {
		sql = "select `addr`,`name`,`activity_id`,`primaries_image` from `activity` where `deadline`>? or `long`=1 order by `activity_id` desc"

		_, err = o.Raw(sql, time.Now().Unix()*1000).QueryRows(&activitys)
	} else {
		sql = "select `addr`,`activity_id`,`primaries_image` from `activity` where addr=? and (`deadline`>? or `long`=1) order by `activity_id` desc"

		_, err = o.Raw(sql, homePagesAddr, time.Now().Unix()*1000).QueryRows(&activitys)
	}

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	sql = "select * from `activity_classifications` left join `classification` on classification.classification_id=activity_classifications.classification_id where activity_classifications.activity_id=? limit 1"
	for i := 0; i < len(activitys); i++ {

		_, err = o.Raw(sql, activitys[i].ActivityId).QueryRows(&activitys[i].Classification)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}
	//for _,activity:=range activitys{
	//	o.Read(activity.Classification)
	//}
	res.Activitys = activitys
	res.Code = "200"
	c.Data["json"] = res

}
